package m202403.d14;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/3/14 10:46
 */
//931. 下降路径最小和
public class Q931 {
    public int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length + 2;
        int[][] dp = new int[m][n];
        for (int i = 1; i < n-1; i++) {
            dp[0][i] = matrix[0][i - 1];
        }
        for (int i = 0; i < m; i++) {
            dp[i][0] = Integer.MAX_VALUE;
            dp[i][n - 1] = Integer.MAX_VALUE;
        }


        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n-1; j++) {
                int temp = matrix[i][j - 1];
                dp[i][j] = temp + Math.min(Math.min(dp[i - 1][j - 1], dp[i - 1][j]), dp[i - 1][j + 1]);
            }
        }
        int r = dp[m - 1][1];
        for (int i = 1; i < n - 1; i++) {
            r = Math.min(r, dp[m - 1][i]);
        }
        return r;
    }
}
